package com.webserver6.core;

import com.webserver6.annotations.Controller;
import com.webserver6.annotations.RequestMapping;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

public class HandlerMapping {
    private static Map<String, Method> mapping = new HashMap<>();
    static {
        initMapping();
    }
    private static void initMapping(){
        try {
            File rootDir = new File(
                    HandlerMapping.class.getClassLoader().getResource(".").toURI()
            );
            File dir = new File(rootDir,"com/webserver6/controller");
            if (dir.exists()){
            File[] subs = dir.listFiles(f->f.getName().endsWith(".class"));
            for (File sub : subs){
                String className = sub.getName().replace(".class","");
                Class cls = Class.forName("com/webserver6/controller."+className);
                if (cls.isAnnotationPresent(Controller.class)) {
                    Method[] methods = cls.getDeclaredMethods();
                    for (Method method : methods) {
                        if (method.isAnnotationPresent(RequestMapping.class)) {
                            RequestMapping rm = method.getAnnotation(RequestMapping.class);
                            String value = rm.value();
                            mapping.put(value, method);
                        }
                    }
                }
                }
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static Method getMethod(String uri){
        return mapping.get(uri);
    }

    public static void main(String[] args) {
        System.out.println(mapping.size());
        System.out.println(mapping);
    }
}
